package com.dengqi.mymodule.activity.loader.applists;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;

import java.lang.ref.WeakReference;
import java.util.List;

import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

/**
 * Created by dell on 2019/5/7
 */
public class AppListCollection implements LoaderManager.LoaderCallbacks<List<ApplicationInfo>> {

    private static final int LOADER_ID = 3;
    private WeakReference<Context> mContext;
    private LoaderManager mLoaderManager;
    private AppListCallbacks mCallbacks;

    @Override
    public Loader<List<ApplicationInfo>> onCreateLoader(int id, Bundle args) {
        Context context = mContext.get();
        return AppListLoader.newInstance(context);
    }

    @Override
    public void onLoadFinished(Loader<List<ApplicationInfo>> loader, List<ApplicationInfo> data) {
        Context context = mContext.get();
        mCallbacks.onAppListLoad(data);
    }

    @Override
    public void onLoaderReset(Loader<List<ApplicationInfo>> loader) {
        Context context = mContext.get();
        mCallbacks.onAppListReset();
    }

    public void init(FragmentActivity activity, AppListCallbacks callbacks) {
        mContext = new WeakReference<Context>(activity);
        mLoaderManager = LoaderManager.getInstance(activity);
        mCallbacks = callbacks;
        mLoaderManager.initLoader(LOADER_ID, null, this).forceLoad();
    }

    public void destroyLoader(){
        mLoaderManager.destroyLoader(LOADER_ID);
    }

    public interface AppListCallbacks {
        void onAppListLoad(List<ApplicationInfo> apps);

        void onAppListReset();
    }
}